var DocData = {
    subclinicId: SessionData.subclinicId,
    userId: baseFn.getQueryString('userId', true),
    userSubclinicId: SessionData.powerSub ? SessionData.powerSub : 0, //权限管理 45 全部门店?
    // userSubclinicId:SessionData.subclinicId, //权限管理 45 全部门店?
    userFrom: 0,
    baseData: {},
    phoneRel: '',
    phoneType: '',
    orderURL: '/xrtn-manager/order/gotoOrderDetail',
    initBase: function (data) {
        //会员基本信息渲染
        var _userData = data, that = this
        if (baseFn.notNull(_userData.userId)) {
            $('.js_phone2_wrap').removeClass('hidden')
            $('.js_phone3_wrap').removeClass('hidden')
        }
        if (_userData.userPhones == '空') {
            _userData.userPhones = null
        }
        if (_userData.userPhoness == '空') {
            _userData.userPhoness = null
        }
        if (baseFn.notNull(_userData.userPhones) && _userData.userPhones != '空') {
            $('.js_userPhones').text(_userData.userPhones).removeClass('hidden')
            $('.js_phone2_wrap .js_phone_btn[rel="3"]').addClass('hidden')
            $('.js_phone2_wrap .js_phone_btn[rel="1"]').removeClass('hidden')
            $('.js_phone2_wrap .js_phone_btn[rel="2"]').removeClass('hidden')
        } else {
            $('.js_userPhones').text('').attr("rel", '').addClass('hidden')
            $('.js_phone2_wrap .js_phone_btn[rel="3"]').removeClass('hidden')
            $('.js_phone2_wrap .js_phone_btn[rel="1"]').addClass('hidden')
            $('.js_phone2_wrap .js_phone_btn[rel="2"]').addClass('hidden')
        }
        if (baseFn.notNull(_userData.userPhoness) && _userData.userPhoness != '空') {
            $('.js_userPhoness').text(_userData.userPhoness).removeClass('hidden')
            $('.js_phone3_wrap .js_phone_btn[rel="3"]').addClass('hidden')
            $('.js_phone3_wrap .js_phone_btn[rel="1"]').removeClass('hidden')
            $('.js_phone3_wrap .js_phone_btn[rel="2"]').removeClass('hidden')
        } else {
            $('.js_userPhoness').text('').attr("rel", '').addClass('hidden')
            $('.js_phone3_wrap .js_phone_btn[rel="3"]').removeClass('hidden')
            $('.js_phone3_wrap .js_phone_btn[rel="1"]').addClass('hidden')
            $('.js_phone3_wrap .js_phone_btn[rel="2"]').addClass('hidden')
        }

        if (baseFn.notNull(_userData.userName)) {
            $('.js_userName').text(_userData.userName)
            $('input[name=userName]').val(_userData.userName)
        } else {
            $('.js_userName').text('无会员名')
        }
        $('input[name=userPhone]').val(_userData.userPhone)
        $('textarea[name=userAddress]').val(_userData.userAddress)
        $('input[name=userBirthday]').val(_userData.userBirthday)
        if (baseFn.notNull(_userData.subclinicId)) {
            that.userSubclinicId = _userData.subclinicId
        }
        $('select.userAddSubclinic').val(that.userSubclinicId).trigger('change')
        if (baseFn.notNull(_userData.userFrom)) {
            that.userFrom = _userData.userFrom
        }
        $('select.userAddfroms').val(that.userFrom).trigger('change')
        $('.userLevel').text(_userData.userLevel)
        $('.userPhone').text(baseFn.getHidePhoneStr(_userData.userPhone))
        $('input[name=imgurl]').val(_userData.userImg)
        $('.userGender').text(_userData.userGender == 0 ? '男' : '女')
        $('.js_userAccount').text(_userData.userAccount)
        $('#outTime').text('到期时间：'+baseFn.timestampToTime(_userData.outTime))
        $('.js_userAddress').text(_userData.userAddress)
        $('.js_cardCount').text(_userData.cardCount)
        $('.js_couponCount').text(_userData.couponCount)
        $('.js_orderCost').text(_userData.orderCost)
        $('.js_createTime').text(_userData.createTimeStr)
        if (baseFn.notNull(_userData.userImg)) {
            $('.js_userImg').css('background-image', 'url(' + _userData.userImg + ')')
            baseFn.imgSize({
                src: _userData.userImg,
                hFn: function (res) {
                    res.dom.css({'background-size': 'auto 100%'})
                },
                wFn: function (res) {
                    res.dom.css({'background-size': '100% auto'})
                },
                ratio: 1,
                otherData: {
                    dom: $('.js_userImg')
                }
            })
        }
        /**
         * userAccount：储值余额
         cardCount：卡项
         couponCount：优惠券
         orderCost：订单金额
         userGender：性别
         */
    },
    initPatients: function (data) {
        var _data = data, _html = ''
        for (var d1 = 0; d1 < _data.length; d1++) {
            _html += '<div class="cols20 rows zcformelm">\
                        <a href="javascript:void(0)" data-vals="' + _data[d1].patientId + '" class="font_blue">宝宝' + (d1 + 1) + '：' + _data[d1].patientName + ' </a>\
                    </div>'
        }
        $('.js_patientlist').html(_html)

    },
    initOrderList: function (data) {
        var _data = data, _html = ''
    },
    initBackAccount: function (data) {
        var that = this, _userData = data
        _userData.subclinicName = SessionData.subclinicName
        $('.backbalancedialog .js_userName').text(_userData.userName);
        $('.backbalancedialog .js_subclinicName').text(_userData.subclinicName)
        $('.backbalancedialog .js_backAccount').text(_userData.userAccount + '元')
        $('.backbalancedialog .js_applyReason').val(baseFn.notNull(_userData.applyReason) ? _userData.applyReason : '')

    }
}
var orderListD = "", patientsD = "", balanceD = "", cardD = ""
/*会员详情*/
//时间控件初始化
baseFn.dateTimePickGroup('.selDateorder', {
    startseled: function () {
        searchOrder()
    },
    endseled: function () {
        searchOrder()
    }
})
var orderListDTdata = {
    userId: DocData.userId,
    limit: 10
}
function searchOrder() {
    var _datas = {
        userId: DocData.userId,
        orderState: 0
    }
    if (baseFn.notNull($('.selstart').val())) {
        _datas.startDate = $('.selstart').val()
    }
    if (baseFn.notNull($('.selend').val())) {
        _datas.endDate = $('.selend').val()
    }
    baseFn.objDelElm(orderListDTdata, 'limit')
    for (var i in _datas) {
        orderListDTdata[i] = _datas[i]
    }
    //console.log(orderListDTdata)
    if (orderListD == '') {
        orderListD = baseFn.rpDataTables('.js_orderlist', {
            ajUrl: baseUrl.base + baseUrl.order + 'selectOrderPageList',
            ajDataSrc: "results.rows",
            ajData: orderListDTdata,
            service: true,
            autoWidth: false,
            select: false,
            scrollY: windowOffsetData.tableHeight(),
            columns: [
                // {"data":null,defaultContent:'',className:'select-checkbox'},
                {
                    data: "orderId",
                    width: '15%',
                    defaultContent: '',
                    className: 'td2p',
                    render: function (data, type, row, meta) {
                        if (!baseFn.notNull(row.orderNo)) {
                            row.orderNo = '无订单号'
                        }
                        if (baseFn.notNull(row.orderTime)) {
                            row.orderTime = baseFn.timestampToTime(row.orderTime)
                        } else {
                            row.orderTime = '无支付时间'
                        }
                        return '<p>订单号：' + row.orderNo + '</p><p>支付时间：' + row.orderTime + '</p>'

                    }
                },
                {
                    data: "orderPayCost", width: '10%', defaultContent: '无', render: function (data, type, row, meta) {
                    return '￥ ' + data
                }
                },
                {
                    "data": "payWay", width: '10%', defaultContent: '无', render: function (data, type, row, meta) {
                    var _txt = ''
                    if (row.orderState == '已关闭') {
                        data = 9
                        row.payWays = 9
                    } else if (row.orderState == '待支付') {
                        data = 8;
                        row.payWays = 8
                    } else if (row.orderState == '已完成') {
                        if (data == 7 || row.payWays == 7) {
                            row.payWays = 7
                            data = 7
                        }
                    }
                    var _payWayStrArr = ['余额', '支付宝', '微信', '现金', 'Pos机', '丁香云优惠券', '商品订单', '他人代付', '待支付', '已关闭', '无']
                    var _payWayStr = baseFn.notNull2(_payWayStrArr[data], true, '其他'),
                        _payWaysStr = baseFn.notNull2(_payWayStrArr[row.payWays], true, '其他')
                    _txt = _payWayStr + ' + ' + _payWaysStr
                    if (_payWayStr == _payWaysStr && _payWayStr != '其他') {
                        _txt = _payWayStr
                    } else if (data == 6) {
                        _txt = _payWaysStr
                    } else if (_payWayStr == '其他' && _payWaysStr != '其他') {
                        _txt = _payWaysStr
                    } else if (_payWayStr != '其他' && _payWaysStr == '其他') {
                        _txt = _payWayStr
                    }
                    return _txt
                }
                },
                {
                    "data": "userName",
                    width: '10%',
                    defaultContent: '无',
                    className: 'td2p',
                    render: function (data, type, row, meta) {
                        return '<p>' + (baseFn.notNull(data) ? data : '无') + '</p><p>' + (baseFn.notNull(row.userPhone) ? baseFn.getHidePhoneStr(row.userPhone) : '无') + '</p>'
                    }
                },
                {"data": "subclinicName", width: '10%', defaultContent: '无'},
                {"data": "doctorName", width: '10%', defaultContent: '无'},
                {
                    "data": "orderId",
                    width: '11%',
                    serviceCost: '无',
                    className: 'td2p',
                    render: function (data, type, row, meta) {
                        var _txt = '<p>' + row.orderState + '</p>'
                        //权限管理 会员中心 - 查看订单详情
                        if (!baseFn.getPower(22)) {
                            _txt += '<a class="font_blue js_order_btn detail" href="javascript:void(0)" data-vals="' + data + '">查看订单</a>';
                        }
                        return _txt
                    }
                }
            ],
            initComplete: function () {

            },
            drawCallback: function (settings) {
                $('.js_order_btn.detail').off('click').on('click', function () {
                    var _id = $(this).data('vals')
                    baseFn.goPath('gotoOrderDetail', {orderId: _id, orderType: 0})
                })
            }
        })
    } else {
        // orderListD.settings()[0].ajax.data = _upData;
        orderListD.ajax.reload()
    }

}
function InfoDetail(type) {
    if (type == 'vip') {
        //消费记录
        searchOrder()
        $.get(baseUrl.base + baseUrl.user + 'selectUserInfo', {userId: DocData.userId}, function (res) {
            if (res.code == '0') {
                //基本信息
                DocData.baseData = res.results.userInfo
                DocData.initBase(res.results.userInfo)
                if (baseFn.notNull(baseFn.getQueryString('edit'))) {
                    $('.js_brandLast').text('编辑会员')

                } else {
                    //储值记录
                    balanceD = baseFn.rpDataTables('.js_balancelist', {
                        datas: res.results.accountList,
                        autoWidth: false,
                        select: false,
                        scrollY: windowOffsetData.tableHeight(5),
                        columns: [
                            {
                                "data": "accountType",
                                width: "10%",
                                defaultContent: '无',
                                render: function (data, type, row, meta) {
                                    if (data == 0) {
                                        return '消费'
                                    } else {
                                        if (row.balancePayCost > 0) {
                                            return '储值'
                                        } else {
                                            return '扣款'
                                        }
                                    }
                                }
                            },
                            {"data": "accountDesc", width: "10%", defaultContent: '无'},
                            {"data": "doctorName", width: "10%", defaultContent: ''},
                            {
                                "data": "accountType",
                                width: "10%",
                                defaultContent: '',
                                className: '',
                                render: function (data, type, row, meta) {
                                    if (data == 0) {
                                        return '- ' + row.balancePayCost
                                    } else {
                                        if (row.balancePayCost > 0) {
                                            return '+' + row.balancePayCost
                                        } else {
                                            return row.balancePayCost
                                        }
                                    }
                                }
                            },
                            {"data": "subclinicName", width: "10%", defaultContent: '无', className: ''}
                            // {"data": "orderState",width:"10%",defaultContent:'',className:'',render:function(data,type,row, meta){
                            //     var _txt = '待付款'
                            //     if(data == 2){
                            //         _txt = '已付款'
                            //     }
                            //     // return '<p>'+ _txt+'<p><p><a class="datatablebtn orderdetails" data href="javascript:void(0)" data-vals="'+ row.orderId+'">订单详情</a></p>'
                            //     return  _txt
                            // }}

                        ],
                        initComplete: function () {

                        },
                        drawCallback: function (settings) {
                            var api = this.api();
                            var rows = api.rows({
                                page: 'current'
                            }).nodes();
                            for (var r1 = 0; r1 < rows.length; r1++) {
                                var _time = baseFn.timestampToTime(rows.data()[r1].createTime)
                                $(rows).eq(r1).before('<tr class="orderlistid_tr"><td colspan="8">' + _time + '&nbsp;&nbsp;&nbsp;&nbsp;' + rows.data()[r1].accountNo + '</td></tr>')
                            }
                            $('.orderdetails').off('click').on('click', function () {
                                var _id = $(this).data('vals')
                                window.location.href = DocData.orderURL + "?orderId=" + _id
                            })
                        }
                    })
                    //计次卡统计
                    $('.js_cardlist_wrap').find('.vipcardelmwrap').remove()
                    for (var i = 0; i < res.results.cardList.length; i++) {
                        var cardLeftTime = res.results.cardList[i].cardLeftTime;
                        var cardCount = res.results.cardList[i].cardCount;
                        var relId = res.results.cardList[i].relId;
                        var _html =
                            '<div class="col-lg-3 vipcardelmwrap" relId="' + relId + '">\
                                <div class="vipcardelm">\
                                    <div class="row">\
                                        <div class="col-sm-12 font_center pd_hor5">' + res.results.cardList[i].cardName + '</div>\
                                    </div>\
                                    <div class="row">\
                                        <div class="col-sm-6 font_right pd_hor5">可用次数:</div>\
                                        <div class="col-sm-6 pd_hor5">' + cardLeftTime + '/' + cardCount + '</div>\
                                    </div>\
                                    <div class="row">\
                                        <div class="col-sm-6 font_right pd_hor5">购买日期:</div>\
                                        <div class="col-sm-6 pd_hor5">' + baseFn.timestampToTime(res.results.cardList[i].createTime) + '</div>\
                                    </div>\
                                    <div class="row" style="color: red;">\
                                        <div class="col-sm-6 font_right pd_hor5">到期日期:</div>\
                                        <div class="col-sm-6 pd_hor5">' + baseFn.timestampToTime(res.results.cardList[i].invalidTime) + '</div>\
                                    </div>';
                        if (!baseFn.getPower(78)) {
                            _html += '\
                                    <div class="row">\
                                        <div class="col-sm-6 font_right pd_hor5">操作:</div>\
                                        <div class="col-sm-6 pd_hor5">';
                            if (cardLeftTime == cardCount) {
                                _html += '<a class="js_carddel" href="javascript:void(0)" style="margin-left: 0.5rem;color: #53C7FF;" relId="' + relId + '" cardCount="' + cardCount + '">删除</a>';
                            }
                            _html += '\
                                        </div>\
                                    </div>\
                                </div>\
                           </div>';
                        }
                        $('.js_cardlist_wrap').append(_html)
                    }
                    // 绑定删除计次卡事件
                    $('.js_carddel').on('click', function () {
                        var relId = $(this).attr("relId");
                        var cardCount = $(this).attr("cardCount");
                        baseFn.dialog({
                            title: '提示',
                            content: '确定删除该计次卡么？',
                            ok: function () {
                                baseFn.$post({
                                    url: baseUrl.card + 'deleteUserCardInfo',
                                    data: {relId: relId},
                                    canNull: true,
                                    calFn: function (res) {
                                        if (res == 0) {
                                            $("div[relId=" + relId + "]").remove();
                                            baseFn.infoDialog('删除成功!');
                                            $('.js_cardCount').text($('.js_cardCount').text() - cardCount);
                                        }
                                    }
                                })
                            }
                        })
                    });
                    //计次卡记录
                    cardD = baseFn.rpDataTables('.js_cardlist', {
                        datas: res.results.cardDetailList,
                        autoWidth: false,
                        select: false,
                        scrollY: 300,
                        columns: [
                            {
                                "data": "accountType",
                                width: "10%",
                                defaultContent: '无',
                                render: function (data, type, row, meta) {
                                    return data
                                    //   if(data == 0){
                                    //     return '消费'
                                    //   }else{
                                    //     return '储值'
                                    //   }
                                }
                            },
                            {"data": "cardName", width: "10%", defaultContent: '无'},
                            {"data": "doctorName", width: "10%", defaultContent: ''},
                            {
                                "data": "accountType",
                                width: "10%",
                                defaultContent: '',
                                className: '',
                                render: function (data, type, row, meta) {
                                    return '-1'
                                    // if(data == 0){
                                    //     return '- ' + row.accountCost
                                    //   }else{
                                    //     return '+ ' + row.accountCost
                                    //   }
                                }
                            },
                            {"data": "subclinicName", width: "10%", defaultContent: '无', className: ''}
                            // {"data": "orderState",width:"10%",defaultContent:'',className:'',render:function(data,type,row, meta){
                            //     var _txt = '待付款'
                            //     if(data == 2){
                            //         _txt = '已付款'
                            //     }
                            //     // return '<p>'+ _txt+'<p><p><a class="datatablebtn orderdetails" data href="javascript:void(0)" data-vals="'+ row.orderId+'">订单详情</a></p>'
                            //     return  _txt
                            // }}

                        ],
                        initComplete: function () {

                        },
                        drawCallback: function (settings) {
                            var api = this.api();
                            var rows = api.rows({
                                page: 'current'
                            }).nodes();
                            for (var r1 = 0; r1 < rows.length; r1++) {
                                var _time = baseFn.timestampToTime(rows.data()[r1].createTime)
                                $(rows).eq(r1).before('<tr class="orderlistid_tr"><td colspan="8">' + _time + '&nbsp;&nbsp;&nbsp;&nbsp;' + rows.data()[r1].orderNo + '</td></tr>')
                            }
                            $('.orderdetails').off('click').on('click', function () {
                                var _id = $(this).data('vals')
                                window.location.href = DocData.orderURL + "?orderId=" + _id
                            })
                        }
                    })
                    //优惠券统计
                    $('.js_couponlist_wrap').find('.vipcardelmwrap').remove()
                    for (var i = 0; i < res.results.couponList.length; i++) {
                        var _html = '<div class="col-lg-3 vipcardelmwrap">\
                                                <div class="vipcardelm">\
                                                    <div class="row">\
                                                        <div class="col-sm-12 font_center pd_hor5">' + res.results.couponList[i].cardName + '</div>\
                                                    </div>\
                                                    <div class="row">\
                                                        <div class="col-sm-6 font_right pd_hor5">截止日期:</div>\
                                                        <div class="col-sm-6 pd_hor5">' + baseFn.timestampToTime(res.results.couponList[i].createTime) + '</div>\
                                                    </div>\
                                                </div>\
                                            </div>'
                        $('.js_couponlist_wrap').append(_html)
                    }
                    //宝宝信息
                    DocData.patientList = res.results.patientList
                    // DocData.initPatients(res.results.patientList)
                    //宝宝列表
                    patientsD = baseFn.rpDataTables('.js_patientlist', {
                        datas: res.results.patientList,
                        autoWidth: false,
                        select: false,
                        scrollY: windowOffsetData.tableHeight('f1'),
                        columns: [
                            {
                                "data": "patientId",
                                width: '20%',
                                defaultContent: '',
                                className: 'imgpwrap img1p',
                                render: function (data, type, row, meta) {
                                    var _img = baseUrl.tempHeadImg
                                    if (baseFn.notNull(row.Img)) {
                                        _img = row.patientImg
                                    }
                                    // return '<img class="imgwrap" src="' + isNull(row.serviceImg, 4) + '">\
                                    return '<div class="datatable_img_div" data-vals="' + _img + '" style="background-image:url(' + _img + ')"></div>\
                                <div class="pwrap">\
                                    <span>' + row.patientName + '</span>\
                                </div>'
                                }
                            },
                            {
                                data: "patientGender", width: "10%", render: function (data, type, row, meta) {
                                if (data != 0) {
                                    return '女'
                                } else {
                                    return '男'
                                }
                            }
                            },
                            {"data": "birthdayStr", width: "10%", defaultContent: '无'},
                            {"data": "orderNum", width: "10%", defaultContent: '0'},
                            {
                                "data": "lastOrderTime",
                                width: "10%",
                                defaultContent: '无',
                                render: function (data, type, row, meta) {

                                    if (data != null) {
                                        return baseFn.timestampToTime(data)
                                    } else {
                                        return '无';
                                    }


                                }
                            },
                            {"data": "lastSubclinic", width: "10%", defaultContent: '无', className: ''}
                        ],
                        initComplete: function () {
                        },
                        drawCallback: function (settings) {
                            //图片初始化
                            $('.datatable_img_div').each(function (ids, val) {
                                baseFn.imgSize({
                                    src: $(val).data('vals'),
                                    hFn: function (res) {
                                        res.dom.css({'background-size': 'auto 100%'})
                                    },
                                    wFn: function (res) {
                                        res.dom.css({'background-size': '100% auto'})
                                    },
                                    ratio: 1,
                                    otherData: {
                                        dom: $(val)
                                    }
                                })
                            })
                        }
                    })
                    //退款申请
                    //DocData.initBackAccount(DocData.baseData)
                }
            }
        }, 'json')
    }
}
if (baseFn.notNull(DocData.userId)) {
    InfoDetail('vip')
}
$('.js_infoedit').on('click', function () {
    baseFn.goPath('gotoAddVip', {userId: DocData.userId, edit: 1})
})

/*会员详情*/
//充值

$('.js_recharge').off('click').on('click', function () {
    baseFn.goPath('gotoHomeRecharge', {userId: DocData.userId})
})
//退款申请
$('.js_backbalance').off('click').on('click', function () {
    if ($('.js_backbalance').hasClass('disabled')) {
        return false
    }
    var _upData = {
        subclinicId: DocData.subclinicId,
        applyUserId: DocData.baseData.userId
    }
    $.get(baseUrl.base + baseUrl.user + 'selectBackCardInfo', _upData, function (res) {
        if (res.code == '0') {
            var _userData = res.results
            DocData.initBackAccount(_userData);
            baseFn.dialog({
                title: '退款申请',
                content: $('.dialogelm.backbalancedialog'),
                width: '40em',
                height: "46vh",
                ok: function () {
                    var _upDatas2 = {
                        applyUserId: DocData.baseData.userId,
                        subclinicId: DocData.subclinicId,
                        applyUserName: _userData.userName,
                        applyUserPhone: _userData.userPhone,
                        applyReason: $('.js_applyReason').val(),
                        backAccount: _userData.userAccount
                    }
                    baseFn.$post({
                        url: baseUrl.user + 'saveBackCardInfo',
                        data: _upDatas2,
                        calFn: function (res) {
                            baseFn.infoDialog('退款申请提交成功！')
                        }
                    })
                },
                cancel: function () {
                }
            })
            $('.backbalancedialog .backaccountbtn').off('click').on('click', function () {
                baseFn.dialog({
                    title: '提示',
                    content: "确定提交退款申请么？",
                    ok: function () {
                        var _upData = {
                            subclinicId: DataCue.subclinicId,
                            applyUserId: _userData.userId,
                            applyUserName: _userData.userName,
                            applyUserPhone: _userData.userPhone,
                            applyReason: $('.js_applyReason').val(),
                            backAccount: _userData.userAccount
                        }
                        $.post(baseUrl.base + baseUrl.user + 'saveBackCardInfo', _upData, function (res) {
                            if (res.code == '0') {
                                $('.js_backbalance').addClass('disabled').text('已申请')
                                baseFn.infoDialog('申请成功！')
                            } else {
                                baseFn.infoDialog(res.info)
                            }
                        }, 'json')
                    }
                })
            })
            // }else{
            //     baseFn.dialog({
            //         content:'因未在该店充值，该用户无法在本店退款。'
            //     })
            // }    
        } else {
            baseFn.infoDialog(res.msg)
        }
    }, 'json')


})
/*会员列表 */
//用户列表
var timeType = $.session.get("vipTimeType") ? parseInt($.session.get("vipTimeType")) : 0;
var userFromType = $.session.get("userFromType") ? parseInt($.session.get("userFromType")) : 0;
var numberStart = $.session.get("vipNumberStart") ? parseInt($.session.get("vipNumberStart")) : 0;
var numberEnd = $.session.get("vipNumberEnd") ? parseInt($.session.get("vipNumberEnd")) : 999999;
var rechargeFrom = $.session.get("rechargeFrom") ? parseInt($.session.get("rechargeFrom")) : 0;
var rechargeTo = $.session.get("rechargeTo") ? parseInt($.session.get("rechargeTo")) : 999999;
var vipSubclinicId = $.session.get("vipSubclinicId") ? parseInt($.session.get("vipSubclinicId")) : DocData.userSubclinicId;
var userPhone = $.session.get("vipUserPhone");
var userDTdata = {
    timeType: timeType,
    userFrom: userFromType,
    numberStart: numberStart,
    userPhone: userPhone,
    numberEnd: numberEnd,
    rechargeFrom: rechargeFrom,
    rechargeTo: rechargeTo,
    // subclinicId:0,
    subclinicId: SessionData.powerSub ? SessionData.powerSub : 0,
    limit: 10
}
userDTdata.subclinicId = vipSubclinicId;
var userDTFnData = {
    ajUrl: baseUrl.base + baseUrl.user + 'selectUserList',
    ajDataSrc: "results.rows",
    ajData: userDTdata,
    service: true,
    sessionPageKey: "vipPage",
    select: 'multi',
    ajType: 'get',
    scrollY: windowOffsetData.tableHeight(),
    autoWidth: false,
    columns: [
        // {"data":null,defaultContent:'',width:'10%',className:'select-checkbox'},
        {
            "data": "userName",
            width: '12%',
            defaultContent: '',
            className: 'imgpwrap img2p',
            render: function (data, type, row, meta) {
                var _img = baseUrl.tempHeadImg
                if (baseFn.notNull(row.userImg)) {
                    _img = row.userImg
                }
                return '<div class="datatable_img_div" data-vals="' + _img + '" style="background-image:url(' + _img + ')"></div>\
                                    <div class="pwrap">\
                                        <span>' + data + '</span>\
                                        <span>' + baseFn.getHidePhoneStr(row.userPhone) + '</span>\
                                    </div>'
            }
        },
        // {"data": "gradeName", width: '8%', defaultContent: ''},
        {
            "data": "orderNumber", width: '6%', defaultContent: '无', render: function (data, type, row, meta) {
            if (data == undefined) {
                data = 0
            }
            return 'X ' + data;
        }
        },
        {
            "data": "orderCost", width: '12%', defaultContent: '无', render: function (data, type, row, meta) {
            if (data == undefined) {
                data = 0
            }
            return '￥ ' + data;
        }
        },{
            "data": "rechargeCost", width: '12%', defaultContent: '无', render: function (data, type, row, meta) {
            if (data == undefined) {
                data = 0
            }
            return '￥ ' + data;
        }
        },
        {"data": "subclinicName", width: '7%', defaultContent: '无'},
        {
            "data": "orderTime", width: '14%', defaultContent: '无', render: function (data, type, row, meta) {
            if (data != undefined) {
                return baseFn.timestampToTime(data);
            }
            // return baseFn.timestampToTime(data);
        }
        },
        {
            "data": "userId", defaultContent: '无', width: '15%', render: function (data, type, row, meta) {
                var _txt = '';
                if (!baseFn.getPower(20)) {
                    _txt = '<button class="datatablebtn detail" data-vals="' + data + '">详情</button>'
                }
                //权限管理 会员中心 - 编辑详情
                if (!baseFn.getPower(68)) {
                    _txt += '<button class="datatablebtn datatablebtnRed edit" data-vals="' + data + '">编辑</button>'
                }
                if (!baseFn.getPower(76)) {
                    _txt += '<button class="datatablebtn datatablebtnGray del" data-vals="' + data + '">删除</button>'
                }
                return _txt;
            }
        }
    ],
    initComplete: function () {
    },

    drawCallback: function (settings) {
        // alert( '表格重绘了' );
        $('.detail').off('click').on('click', function () {
            var _id = $(this).data('vals')
            DocData.userId = _id
            baseFn.goPath('gotoVipDetail', {userId: _id})
            // InfoDetail('vip')
        })
        $('.edit').off('click').on('click', function () {
            var _id = $(this).data('vals')
            DocData.userId = _id
            baseFn.goPath('gotoAddVip', {userId: _id, edit: 1})
        })
        $('.del').off('click').on('click', function () {
            var _id = $(this).data('vals')
            var _tr = $(this).parents('tr')
            // InfoDetail('vip')
            baseFn.dialog({
                title: '确定删除该会员么？',
                content: '若该会员没有已完成订单，将删除该会员下的宝宝，余额，计次卡，预约记录等相关信息。否则将无法删除。',
                ok: function () {
                    baseFn.$post({
                        url: baseUrl.user + 'deleteUserInfo',
                        data: {userId: _id},
                        canNull: true,
                        calFn: function (res) {
                            if (res == 0) {
                                userDT.row(_tr).remove().draw();
                                baseFn.infoDialog('删除成功!');
                            }
                        }
                    })
                },
                cancel: function () {
                }
            })
        })
        //图片初始化
        $('.datatable_img_div').each(function (ids, val) {
            baseFn.imgSize({
                src: $(val).data('vals'),
                hFn: function (res) {
                    res.dom.css({'background-size': 'auto 100%'})
                },
                wFn: function (res) {
                    res.dom.css({'background-size': '100% auto'})
                },
                ratio: 1,
                otherData: {
                    dom: $(val)
                }
            })
        })
    }
}
//权限管理 会员中心 - 查看会员详情
// if (baseFn.getPower(20)) {
//     userDTFnData.columns.pop()
//     $('.js_power_20').remove()
// }

var userDT = baseFn.rpDataTables('.user_list', userDTFnData)
$('.js_paycount_input,.js_paycount_input2').on('change', function () {
    // $(this).parents('li').siblings('all').removeClass('active')
    var vipNumberStart = $('.js_paycount_input').val();
    var vipNumberEnd = $('.js_paycount_input2').val();
    $.session.set("vipNumberStart", vipNumberStart);
    $.session.set("vipNumberEnd", vipNumberEnd);
    $.session.set("vipNumberStart", vipNumberStart);
    $.session.set("vipNumberEnd", vipNumberEnd);
    listSearchingFn.vip('.searchgroup.vipsearch')
})
$('.js_recharge_input,.js_recharge_input2').on('change', function () {
    // $(this).parents('li').siblings('all').removeClass('active')
    var rechargeFrom = $('.js_recharge_input').val();
    var rechargeTo = $('.js_recharge_input2').val();
    $.session.set("rechargeFrom", rechargeFrom);
    $.session.set("rechargeTo", rechargeTo);
    userDTFnData.ajData.rechargeFrom = rechargeFrom;
    userDTFnData.ajData.rechargeTo = rechargeTo;
    listSearchingFn.vip('.searchgroup.vipsearch')
})
$('.searchwrap.js_paycount').find('.searchelm a').on('click', function () {
    $(this).parents('li').addClass('active')
    $(this).parents('li').siblings('.searchelm input').val('')
})
//右上角搜索
$('.bespeak_search_button').click(function () {
    $.session.set("vipUserPhone", $('#search').val());
    listSearchingFn.vip('.searchgroup.vipsearch')
});

$("#search").keydown(function (event) {
    if (event.keyCode == "13") {
        $.session.set("vipUserPhone", $('#search').val());
        listSearchingFn.vip('.searchgroup.vipsearch')
    }
});

//    新加开始
var timeType = $.session.get("vipTimeType") ? parseInt($.session.get("vipTimeType")) : 0;
var userFromType = $.session.get("userFromType") ? parseInt($.session.get("userFromType")) : 0;
var numberStart = $.session.get("vipNumberStart") ? parseInt($.session.get("vipNumberStart")) : 0;
var numberEnd = $.session.get("vipNumberEnd") ? parseInt($.session.get("vipNumberEnd")) : 0;

userDTFnData.ajData.subclinicId = vipSubclinicId;
userDTFnData.ajData.timeType = timeType;
userDTFnData.ajData.userFrom = userFromType;
userDTFnData.ajData.userPhone = $.session.get("vipUserPhone");
userDTFnData.ajData.numberStart = numberStart;
if (numberEnd > 0) {
    userDTFnData.ajData.numberEnd = numberEnd;
} else {
    userDTFnData.ajData.numberEnd = 99999;
}

initializationView();

function initializationView() {
    // 时间分类
    var timeType = $.session.get("vipTimeType") ? parseInt($.session.get("vipTimeType")) : 0;
    var userFromType = $.session.get("userFromType") ? parseInt($.session.get("userFromType")) : 0;
    switch (timeType) {
        case 0:
            $('#timeType_one').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 1:
            $('#timeType_two').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 2:
            $('#timeType_three').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 3:
            $('#timeType_four').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 4:
            $('#timeType_five').addClass('active').siblings('.searchelm').removeClass('active');
            break
    }
    switch (userFromType) {
        case 0:
            $('#userFormType_0').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 1:
            $('#userFormType_1').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 2:
            $('#userFormType_2').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 3:
            $('#userFormType_3').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 4:
            $('#userFormType_4').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 5:
            $('#userFormType_5').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 6:
            $('#userFormType_6').addClass('active').siblings('.searchelm').removeClass('active');
            break
        case 7:
            $('#userFormType_7').addClass('active').siblings('.searchelm').removeClass('active');
            break
    }
    // 就诊次数
    var numberStart = $.session.get("vipNumberStart") ? parseInt($.session.get("vipNumberStart")) : 0;
    var numberEnd = $.session.get("vipNumberEnd") ? parseInt($.session.get("vipNumberEnd")) : "";
    $(".js_paycount_input").val(numberStart);
    $(".js_paycount_input2").val(numberEnd);
    // 充值金额
    var rechargeFrom = $.session.get("rechargeFrom") ? parseInt($.session.get("rechargeFrom")) : 0;
    var rechargeTo = $.session.get("rechargeTo") ? parseInt($.session.get("rechargeTo")) : "";
    $(".js_recharge_input").val(rechargeFrom);
    $(".js_recharge_input2").val(rechargeTo);
    $('#search').val($.session.get("vipUserPhone"));
}

//    新加结束

//过滤按钮  jyf
$('.searchgroup.vipsearch').find('.timeType').on('click', function () {
    var _value = $(this).attr("data-vals");
    if (_value != undefined) {
        $.session.set("vipPage",1);
        $.session.set("vipTimeType", _value ? _value : 0);
    }
    listSearchingFn.vip('.searchgroup.vipsearch')
})
// jyf
$('.searchgroup.vipsearch').find('.flagType').on('click', function () {
    var _value = $(this).attr("data-vals");
    if (_value != undefined) {
        $.session.set("vipPage",1);
        $.session.set("userFromType", _value ? _value : 0);
    }
    listSearchingFn.vip('.searchgroup.vipsearch')
})

//门店
baseFn.rpSelect('.subclinicselect', {
    url: baseUrl.base + baseUrl.subclinic + 'selectSubclinicList',
    idKey: 'subclinicId',
    textKey: 'subclinicName',
    calFn: function (dom) {
        //权限管理 45 全部门店
        if (SessionData.powerSub) {
            $('.subclinicselect').val(SessionData.powerSub).trigger('change')
        }
        dom.val(vipSubclinicId).trigger('change')
    },
    selFn: function () {
        listSearchingFn.vip('.searchgroup.vipsearch');
        $.session.set("vipSubclinicId", $('.subclinicselect').val());
        $.session.set("vipSubclinicName", $('.subclinicselect option:selected').text());
    }
})
/*会员列表 */
/*添加会员*/
baseFn.rpSelect('.userAddSubclinic', {
    url: baseUrl.base + baseUrl.subclinic + 'selectSubclinicList',
    idKey: 'subclinicId',
    textKey: 'subclinicName',
    calFn: function () {
        $('select.userAddSubclinic').val(DocData.userSubclinicId).trigger('change')
    },
    selFn: function () {
    }
})
baseFn.rpSelect('.userAddfroms', {
    url: baseUrl.base + baseUrl.init + 'selectSysList',
    dataSrc: 'results.fromList',
    idKey: 'fromId',
    textKey: 'fromName',
    calFn: function () {
        $('select.userAddfroms').val(DocData.userFrom).trigger('change')
    },
    selFn: function () {
    }
})
/* 操作其他联系人*/
$('.js_phone_btn').on('click', function () {
    var $this = $(this), _phoneRel = $(this).parent('div').find('.js_other_phone').data('vals'),
        _type = $(this).attr('rel');
    DocData.phoneRel = _phoneRel
    DocData.phoneType = _type
    var infoData = {
        tit: '',
        text: '',
        okTxt: ''
    }
    // console.log(_phoneRel)
    $('input.js_otherPhone').val($(this).siblings('.js_other_phone').text())
    $('input.js_checkId').val('')
    if (_type == 1) {
        //修改
        infoData.tit = '修改联系人'
        infoData.okTxt = '修改'
        $('.js_otherPhone').prop('disabled', false)
    } else if (_type == 2) {
        //解绑
        infoData.tit = '解绑联系人'
        infoData.okTxt = '解绑'
        $('.js_otherPhone').prop('disabled', true)
    } else if (_type == 3) {
        //绑定
        infoData.tit = '绑定联系人'
        infoData.okTxt = '绑定';
        $('.js_otherPhone').prop('disabled', false)
    }
    var b = baseFn.dialog({
        title: infoData.tit,
        width: '35rem',
        okValue: infoData.okTxt,
        content: $('.eiditphone'),
        ok: function () {
            var _txt = '';
            var _phone = $('input.js_otherPhone').val();
            var _upDatas = {
                userCode: $('input.js_checkId').val()
            }
            if (_type != 2) {
                if (_phoneRel == 2) {
                    _upDatas.userPhoness = _phone
                } else {
                    _upDatas.userPhones = _phone
                }
            } else {
                if (_phoneRel == 2) {
                    _upDatas.userPhoness = '空'
                } else {
                    _upDatas.userPhones = '空'
                }
            }
            if (baseFn.notNull(DocData.userId)) {
                _upDatas.userId = DocData.userId
            }
            if (!baseFn.notNull(_upDatas.userCode)) {
                _txt = '请输入验证码'
            } else if (!baseFn.notNull(_phone) && _type != 2) {
                _txt = '请输入手机号'
            } else if (!/^13[0-9]{9}$|14[0-9]{9}|17[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$/.test(_phone) && _type != 2) {
                _txt = '请输入正确的手机号格式'
            }
            if (baseFn.notNull(_txt)) {
                baseFn.infoDialog(_txt)
                return false
            }
            baseFn.$post({
                url: baseUrl.user + 'updateUserInfo',
                data: _upDatas,
                canNull: true,
                calFn: function (res) {
                    baseFn.infoDialog(infoData.okTxt + '成功！', function () {
                        if (_type != 2) {
                            if (_phoneRel == 2) {
                                DocData.baseData.userPhoness = _phone
                            } else {
                                DocData.baseData.userPhones = _phone
                            }
                        } else {
                            if (_phoneRel == 2) {
                                DocData.baseData.userPhoness = null
                            } else {
                                DocData.baseData.userPhones = null
                            }
                        }
                        DocData.initBase(DocData.baseData)
                        b.close()
                    })

                }
            })
            return false
        },
        cancel: function () {
            if (time != '') {
                _time = 60
                window.clearInterval(time)
                $('.js_getCheckBtn').removeClass('disabled').text('发送验证码')
            }
        }
    })
})
//获取验证码
var time = '', _time = 60
$('.js_getCheckBtn').on('click', function () {
    var _upDatas = {
        userId: DocData.userId
    }
    var _phone = $('input.js_otherPhone').val();
    var _txt = ''
    if (!baseFn.notNull(_phone) && DocData.phoneType != 2) {
        _txt = '请输入手机号'
    } else if (!/^13[0-9]{9}$|14[0-9]{9}|17[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$/.test(_phone) && _type != 2) {
        _txt = '请输入正确的手机号格式'
    }
    if (baseFn.notNull(_txt)) {
        baseFn.infoDialog(_txt)
        return false
    }
    if (DocData.phoneRel == 2) {
        _upDatas.userPhoness = _phone
    } else {
        _upDatas.userPhones = _phone
    }
    var $this = $(this)
    if ($this.hasClass('disabled')) {
        return false
    } else {
        baseFn.$post({
            url: 'user/updateUserSendCode',
            data: _upDatas,
            canNull: true,
            calFn: function (res) {
                baseFn.infoDialog('成功发送验证码')
                $this.addClass('disabled')
                time = setInterval(function () {
                    $this.text('还有' + _time + '秒')
                    _time--
                    if (_time == '0') {
                        _time = 60;
                        $this.removeClass('disabled').text('重新获取')
                        window.clearInterval(time);
                        time = ''
                    }
                }, 1000)
            }
        })
    }
})
/* 操作其他联系人*/
//图片上传
$('.Js_preview').on('click', function () {
    $('#Js_previewImgNew').trigger('click')
})
function zcuploadImageCover(e) {
    baseFn.imgUpload($(e).parents('form').attr('id'), function (res) {
        // $(e).siblings('.Js_preview').find('img').attr('src',res.url)
        $(e).siblings('.Js_preview').css('background-image', 'url(' + res.url + ')')
        $(e).parents('form').siblings('input[name=imgurl]').val(res.url)
        baseFn.imgSize({
            src: res.url,
            hFn: function (res) {
                res.dom.css({'background-size': 'auto 100%'})
            },
            wFn: function (res) {
                res.dom.css({'background-size': '100% auto'})
            },
            ratio: 1,
            otherData: {
                dom: $(e).siblings('.Js_preview')
            }
        })
    })
}
var myValidform = $(".js_newvip").Validform({
    tiptype: 2,
    datatype: {
        putso: function (gets, obj, curform, regxp) {
            /*参数gets是获取到的表单元素值，
             obj为当前表单元素，
             curform为当前验证的表单，
             regxp为内置的一些正则表达式的引用。*/
            var _checkpwrap = obj.parents('.checkpwrap')
            var _type = _checkpwrap.find('.checkp').val()
            var _userid = _checkpwrap.find('.userid').val()
            var _post = _checkpwrap.find('.post').val()
            var reg1 = regxp["*"],
                reg2 = /[\d]{7}/,
                mobile = curform.find(".mobile");
            if (obj) {
                if (_type == '1') {
                    //人
                    //console.log(_userid)
                    if (reg1.test(_userid)) {
                        return true;
                    }
                } else if (_type == '3') {
                    //岗位
                    if (reg1.test(_post)) {
                        return true;
                    }
                }
            }
            return false;
        },
        ztreegroup: function (gets, obj, curform, regxp) {
            console.log(gets)
            if (gets == '') {
                return false
            } else {
            }
        },
        select2: function (gets, obj, curform, regxp) {
            if (gets.length == 0) {
                obj.siblings('.select2').find('.select2-selection').css('borderColor', 'red')
                return false
            } else {
                obj.siblings('.select2').find('.select2-selection').css('borderColor', '#ccc')
            }
        }
    }
});
baseFn.dateTimePick('.userBirthday', {})
//图片上传-宝宝
$('.Js_preview_patient').on('click', function () {
    $('#Js_previewImgNew_patient').trigger('click')
})
//新增宝宝验证函数
var patientValidform = $(".dialogelm.base").Validform({
    tiptype: 3
});
baseFn.dateTimePick('.patientBirthday', {})
$('.js_newvip .edit_ok').on('click', function () {
    if (!myValidform.check()) {
        return false
    }
    var _upDatas = {
        userName: $.trim($('input[name=userName]').val()),
        userPhone: $.trim($('input[name=userPhone]').val()),
        subclinicId: $('select[name=subclinic]').val(),
        userBirthday: $('input[name=userBirthday]').val(),
        userAddress: $('textarea.userAddress').val(),
        userAddfroms: $('select[name=froms]').val(),
        userImg: $('input[name=imgurl]').val()
    }
    var _url = 'saveUserInfo', _txt = '添加成功'
    if (baseFn.notNull(DocData.userId)) {
        _upDatas.userId = DocData.userId
        _url = 'updateUserInfo',
            _txt = '修改成功'
    }
    // return false
    $.post(baseUrl.base + baseUrl.user + _url, _upDatas, function (res) {
        if (res.code == '0') {
            if (baseFn.notNull(res.results)) {
                DocData.userId = res.results
                baseFn.dialog({
                    title: "提示",
                    content: '是否为该会员添加宝宝？',
                    okValue: '新增宝宝',
                    ok: function () {
                        //病人基本信息弹窗
                        var baseD = baseFn.dialog({
                            title: '新增宝宝',
                            width: '30em',
                            content: $('.dialogelm.base'),
                            ok: false
                        })
                        //取消
                        $('.dialogelm.base .buttongroup .edit_cancel').off('click').on('click', function () {
                            baseD.close()
                            baseFn.goPath('gotoVip')
                        })
                        //确定
                        $('.dialogelm.base .buttongroup .edit_ok').off('click').on('click', function () {
                            // $('.dialogelm.base .buttongroup .edit_ing').addClass('hidden')
                            if (!patientValidform.check()) {
                                return false
                            }
                            var _upDatas = {
                                userId: DocData.userId,
                                userName: $('.dialogelm.base .patientName').val(),
                                userGender: $('.dialogelm.base select.patientGender').val(),
                                userBirthday: $('.dialogelm.base .patientBirthday').val(),
                                userAddress: $('.dialogelm.base .patientAddress').val(),
                                userBodyWeight: $('.dialogelm.base .patientBodyWeight').val(),
                                userHeight: $('.dialogelm.base .patientHeight').val()
                            }
                            // if (patientData.imgChange) {
                            //     _upDatas.userImg = $('input[name=imgurl]').val()
                            // }

                            $.post(baseUrl.base + baseUrl.patient + 'savePatientInit', _upDatas, function (res) {
                                if (res.code == '0') {
                                    baseFn.infoDialog(res.msg, function () {
                                        baseFn.goPath('gotoVip')
                                    }, 1000)
                                    baseD.close()
                                }
                            }, 'json')

                        })
                    },
                    cancelValue: '返回列表',
                    cancel: function () {
                        baseFn.goPath('gotoVip')
                    }
                })
            } else {
                baseFn.infoDialog(_txt, function () {
                    baseFn.goPath('gotoVip')
                });
            }

        } else {
            baseFn.infoDialog(res.msg);
        }
    }, 'json')
})
$('.js_newvip .edit_cancel').on('click', function () {
    baseFn.goPath('gotoVip')
})
//会员详情列表 tab切换
$('.bespeak_change_list_actve').on('click', function () {
    var thisIndex = $(this).index();
    $(this).addClass("active_bgc").siblings().removeClass("active_bgc");
    $('.js_tabcnt').eq(thisIndex).removeClass('hidden').siblings(".js_tabcnt").addClass('hidden');
})
$('.js_cardlist_wrap').css('height', windowOffsetData.tableHeight() - 140)
$('.js_couponlist_wrap').css('height', windowOffsetData.tableHeight() - 140)
//表格自适应
window.onresize = function () {
    windowOffsetData.refresh();
    $('.js_cardlist_wrap').css('height', windowOffsetData.tableHeight() + 40)
    $('.js_couponlist_wrap').css('height', windowOffsetData.tableHeight() + 40)
    if (baseFn.notNull(userDT)) {
        $(userDT.table().body()).parents('.dataTables_scrollBody').css('max-height', windowOffsetData.tableHeight());
        userDT.draw(false);
    }
    if (baseFn.notNull(orderListD)) {
        $(orderListD.table().body()).parents('.dataTables_scrollBody').css('max-height', windowOffsetData.tableHeight());
        orderListD.draw(false);
    }
    if (baseFn.notNull(patientsD)) {
        $(patientsD.table().body()).parents('.dataTables_scrollBody').css('max-height', windowOffsetData.tableHeight('f1'));
        patientsD.draw(false);
    }
    if (baseFn.notNull(balanceD)) {
        $(balanceD.table().body()).parents('.dataTables_scrollBody').css('max-height', windowOffsetData.tableHeight(5));
        balanceD.draw(false);
    }
}